<?php
	//The math expression must to be between '(' and ')' 
	class MATH_REPLACE
	{
		private $inputString;
		
		public function __construct($inputString = "(2+2)"){
			$this->inputString = $inputString;
		}
		
		// Return the result string after replacing the maths expressions
		public function replace($inputString = null){
			if(!isset($inputString))
			{
				$inputString = $this->inputString;
			}
			$Matchs = preg_match_all("/\(+[0-9+\s+\-.*\/()%]+\)/", $inputString, $mMatchs);
			for ($i=0;$i<$Matchs; $i++){
				$Formula = str_replace(" ", "", $mMatchs[0][$i]);
				$Formula = preg_replace("/([+-])([0-9]+)(%)/", "*(1\$1.\$2)", $Formula);
				$Formula = preg_replace("/([0-9]+)(%)/",".\$1",$Formula);
				eval("\$Result=" . $Formula . ";");
				$Pos = strpos($inputString, $mMatchs[0][$i]);
				$inputString = substr_replace($inputString, $Result, $Pos, strlen($mMatchs[0][$i]));
			}
			return $inputString;
		}
	}
?>
 